package com.spring.pay.cmb.controller.cmb;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jdom.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.spring.pay.cmb.service.ICmbpayService;
import com.spring.pay.weixin.util.XMLUtil;
import com.spring.util.CommonResult;
import com.spring.util.ConstantsStatus;

/**
 * @author 作者 E-mail: liuyang
 * @date 创建时间：2016年10月24日 下午12:03:03
 * @version 2.0
 * @parameter
 * @since
 * @return
 */
@RestController
@RequestMapping("/cmbpay")
public class CmbpayApiController {
	private Logger LOGGER = Logger.getLogger(CmbpayApiController.class);
	@Autowired
	private ICmbpayService cmbpayServiceImpl;

	/**
	 * 一网通支付完成回调
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/receiveNotify")
	public void receiveNotify(HttpServletRequest request, HttpServletResponse response) {
		LOGGER.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 一网通支付完成...");

		try {
			String queryStr = request.getQueryString();
			String str = cmbpayServiceImpl.receiveNotify(queryStr, request.getParameterMap());

		} catch (Exception e) {
			LOGGER.error("一网通回调返回系统异常！");
		}
	}

	/**
	 * 一网通签约回调
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/rocResultNotify")
	public void rocResultNotify(HttpServletRequest request, HttpServletResponse response) {
		LOGGER.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 一网通来回调啦...");

	}

	/**
	 * 一网通订单查询
	 * 
	 * @return
	 */
	@RequestMapping("/queryCmbOrderInfo")
	public CommonResult<Object> queryCmbOrderInfo(String orderNo) {
		CommonResult<Object> commonResult = new CommonResult<Object>();
		if (orderNo == null) {
			commonResult.setResult(ConstantsStatus.SC5001, "订单号不能为空", false);
			return commonResult;
		}

		String msg = cmbpayServiceImpl.queryCmbOrder(orderNo);
		Map map = null;
		try {
			map = XMLUtil.doXMLParse(msg);
			StringBuffer buff = new StringBuffer("<xml>");
			buff.append((String) map.get("Body"));
			buff.append("</xml>");
			map = XMLUtil.doXMLParse(buff.toString());

		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		commonResult.setResult(ConstantsStatus.SC2000, "一网通订单查询成功", true, map);
		return commonResult;
	}

}
